package com.whu.bookstore.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by 11956 on 2017/4/16.
 * md5工具类
 */
public class MD5Util {
    private static MessageDigest messageDigest;
    //private static final char[] hexChars = {'0','1','2','3','4','5','6','7',
    //'8','9','a','b','c','d','e','f'};
    private static StringBuilder builder = new StringBuilder();

    static {
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static String getMD5(String source) {
        try {
            byte[] result = messageDigest.digest(source.getBytes("utf-8"));
            for (int i = 0; i < result.length; i++) {
                int value = result[i];
                if (value < 0)
                    value += 256;
                String hexString = Integer.toHexString(value);
                if (hexString.length() == 1) {
                    builder.append('0');
                    builder.append(hexString);
                } else {
                    builder.append(hexString);
                }
            }
            String temp = builder.toString();
            builder.setLength(0);
            return temp;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
